package com.dldata.devtools30.controller.devtexcel;

import com.alibaba.fastjson.JSON;
import com.dldata.devtools30.common.EnumUtils;
import com.dldata.devtools30.controller.DevBase30Controller;
import com.dldata.devtools30.entity.*;
import com.dldata.devtools30.repository.devtexcel.DevtExcelFieldDao;
import com.dldata.devtools30.repository.metadata.DevtModelMetadataTableDao;
import com.dldata.devtools30.repository.devtexcel.DevtExcelDao;
import com.dldata.devtools30.repository.devtexcel.DevtExcelTypeDao;
import com.dldata.devtools30.repository.sysform.DevtFormMetadataDao;
import com.dldata.devtools30.service.metadata.DevtModelMetadataTableService;
import com.dldata.devtools30.service.sysform.DevtFormListTemplateService;
import com.dldata.devtools30.service.sysform.DevtFormTypeService;
import com.dldata.devtools30.utils.Result;
import com.dldata.devtools30.utils.StringUtil;
import com.dldata.devtools30.utils.dataexport.DataExportUtil;
import com.dldata.devtools30.utils.dataexport.TableConfig;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Date;
import java.util.*;

/**
 *
 */
@Controller
@RequestMapping(value = "/DevtExcelController")
public class DevtExcelController  extends DevBase30Controller {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private DevtFormListTemplateService sysCrfFormListTemplateService;


    @Autowired
    DevtModelMetadataTableService metadataTableService;
    @Autowired
    DevtFormMetadataDao sysCrfFormMetadataDao;
    @Autowired
    private DevtFormTypeService sysCrfFormTypeService;

    @Autowired
    private DevtExcelDao devtexcelDao;


    @Autowired
    private DevtExcelTypeDao devtexcelTypeDao;

    @Autowired
    private DevtExcelFieldDao devtExcelFieldDao;

    @RequestMapping(value = "/toPage")
    public String toPage(Model model) {
        return "thymeleaf/devtools30/devtexcel/devtExcelIndex";
    }

    @RequestMapping(value = "/optPage")
    public String optPage(Model model, String id) {
        DevtFormListtemplateEntity sysCrfFormListtemplateEntityTmp = sysCrfFormListTemplateService.getTemplateById(id);

        model.addAttribute("devtExcelEntity", StringUtil.escape(JSON.toJSONString(sysCrfFormListtemplateEntityTmp)));
        model.addAttribute("id", id);
        return "thymeleaf/devtools30/devtexcel/devtExcelOpt";
    }

    @RequestMapping(value = "/toEdit")
    public String toEdit(String id, String typeId, Model model) {
        DevtExcelEntity entity = new DevtExcelEntity();
        if (!StringUtil.isNullOrSpace(id)) {
            entity = devtexcelDao.getById(id);
        }
        model.addAttribute("data", entity);

        model.addAttribute("typeId", typeId);

        List<DevtModelMetadataTableEntity> tableServiceAll
                = metadataTableService.getAll(Arrays.asList(new String[]{EnumUtils.ModelTypeEnum.填报表单.name()}));
        model.addAttribute("mtableList", tableServiceAll);

        model.addAttribute("typeList", devtexcelTypeDao.getAllFormType());


        return "thymeleaf/devtools30/devtexcel/devtExcelEdit";
    }


    @RequestMapping(value = "/toClone")
    public String toClone(Model model, String templateId) {
        model.addAttribute("templateId", templateId);
        return "thymeleaf/devtools30/sysform/v_SysFormTemplateClone";
    }


    @RequestMapping(value = "/getExcelList")
    @ResponseBody
    public Result getExcelList(String typeId, String search, String formid) {
        search = "%" + search + "%";
        List<Map> maps = StringUtil.isEmptyOrLength0(typeId) ? devtexcelDao.findNameList(search) : devtexcelDao.findByList(typeId, search);
        if (maps.size() == 1 && maps.get(0).get("typeName") == null) {
            maps = new ArrayList<Map>();
        }
        return Result.ok(maps);

    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public Result save(DevtExcelEntity devtexcelEntity, HttpServletRequest request, HttpServletResponse response, @RequestParam Map<String, Object> params) throws Exception {
        try {
            if (StringUtil.isNullOrSpace(devtexcelEntity.getId())) {
                devtexcelEntity.setId(UUID.randomUUID().toString());
                devtexcelEntity.setCreateTime(new Date(new java.util.Date().getTime()));
            } else {
                DevtExcelEntity entity = devtexcelDao.getById(devtexcelEntity.getId());
                devtexcelEntity.setContentType(entity.getContentType());
                devtexcelEntity.setDatacontent(entity.getDatacontent());
                devtexcelEntity.setFileLength(entity.getFileLength());
                devtexcelEntity.setFileNameOrg(entity.getFileNameOrg());
                devtexcelEntity.setCreateTime(entity.getCreateTime());

            }

            devtexcelDao.save(devtexcelEntity);

            return Result.ok();
        } catch (Exception ex) {

            logger.error("【执行" + this.getClass().getName() + ".save() 方法失败 】异常：" + ex.getMessage());
            return Result.error("操作错误，请稍候再试！");
        }

    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public Result deltemplet(String id, HttpServletRequest request,
                             HttpServletResponse response) throws Exception {
        String result;
        try {
            List<DevtExcelFieldEntity> byExcelXh = devtExcelFieldDao.findByExcelXh(id);
            if (byExcelXh.size()>0){
                return Result.error("请先删除导入配置");
            }
            devtexcelDao.deleteById(id);

            return Result.ok();
        } catch (Exception ex) {

            logger.error("【执行" + this.getClass().getName() + ".delete() 方法失败 】异常：" + ex.getMessage());
            return Result.error("系统错误，请稍候再试！");
        }


    }

    @RequestMapping(value = "/export")
    public void export(@RequestParam Map<String, String> paramMap, HttpServletResponse response) throws Exception {

        String ids = paramMap.get("ids");
        if(!StringUtil.isEmptyOrLength0(ids)&&ids.endsWith(",")){
            ids=ids.substring(0,ids.length()-1);
        }
        String[] split = ids.split(",");

        TableConfig tableConfig=new TableConfig("devt_excel",
                "EXCEL配置表","id","",Boolean.TRUE);
        tableConfig.setSubtableList(new ArrayList<>());
        tableConfig.getSubtableList().add(new TableConfig("devt_excel_field",
                "EXCEL字段对应配置表","excel_id","id",Boolean.TRUE));
        tableConfig.getSubtableList().add(new TableConfig("devt_excel_type",
                "EXCEL分类配置表","id","type_id",Boolean.TRUE));


        List<TableConfig> tableConfigList=new ArrayList();
        tableConfigList.add(tableConfig);
        HashMap<String,List<Object>> dataMap=new HashMap<>();
        dataMap.put(tableConfig.getTablename(),new ArrayList<>());
        dataMap.get(tableConfig.getTablename()).addAll(Arrays.asList(split));

        DataExportUtil dataExportUtil = DataExportUtil.createDataExportUtil(jdbcTemplate.getDataSource(), true);
        String sqlContent=dataExportUtil.exportData(tableConfigList,dataMap,new ArrayList<>());
        String  contentType="text/sql";
        response.setContentType(StringUtil.isEmptyOrLength0(contentType)?"application/octet-stream":contentType);
        String formid = ids.replaceAll(",", "_");
        formid=formid.indexOf("_")>0?formid.substring(0,formid.indexOf(",")):formid;
        response.addHeader("Content-Disposition","attachment;filename="+java.net.URLEncoder.encode("表单配置导出_"+formid +".sql","UTF-8"));
        response.setCharacterEncoding("utf-8");
        InputStream inputStream=new ByteArrayInputStream(sqlContent.getBytes(StandardCharsets.UTF_8));
        byte[] byteData=new byte[1024*1024*3];
        int count=-1;
        ServletOutputStream servletOutputStream= response.getOutputStream();
        while ((count=inputStream.read(byteData))!=-1){
            servletOutputStream.write(byteData,0,count);
        }
        servletOutputStream.flush();
    }

}
